<template>
  <!-- 已完善 -->
  <div style="margin-top: 20px">
    <Spin size="large" fix v-if="spinShow"></Spin>
    <Row
      v-if="!batchBtn"
      style="padding-bottom: 16px"
      type="flex"
      align="middle"
    >
      <div>选择销售区域:</div>
      <a @click="showSelectArea" style="margin-left: 20px">选择销售区域</a>
      <div style="margin-left: 20px">{{ areaNames }}</div>
    </Row>
    <Button v-if="batchBtn" type="primary" @click="gotoPage">前往新增 </Button>
    <div v-else>
      <Card
        v-for="(gongitem, i) in gong"
        :key="i"
        dis-hover
        style="margin-top: 20px"
      >
        <div>
          <Row class="cardRow" type="flex" justify="space-between">
            <Col flex="true">
              <supply
                @getName="getSupply"
                :supplyEditName="gongitem.supplyName"
              ></supply>
            </Col>
            <Col flex="true">
              运费承担方：<span>{{ freightPayer || gongitem.whoPayFreight }}</span>
            </Col>
          </Row>
          <Row class="cardRow format_table_wrap">
            <div class="min-title">供货信息维护如下：</div>
            <skus-table
              :loading="tableLoading"
              :table-height="450"
              :data-source="gongitem.supplySkuInfoList"
              :columns="supplySkuInfoColumns"
            />
          </Row>
          <Row type="flex" align="middle" class="cardRow">
            <div>供货价格方式：</div>
            <RadioGroup
              v-model="gongitem.supplyPriceType"
              @on-change="handleSupplyMethodChange"
            >
              <Radio label="1">统一进价</Radio>
              <Radio label="2">区域进价</Radio>
            </RadioGroup>
          </Row>
          <Row class="cardRow" type="flex" align="middle">
            <div>设置参照城市关系:</div>
            <Button
              type="primary"
              style="margin-left: 20px"
              @click="handleSetCityLink(i, gongitem)"
              >设置
            </Button>
          </Row>
          <Row class="cardRow format_table_wrap">
            <div class="min-title">供货价格相关信息如下:</div>
            <skus-table
              :loading="tableLoading"
              :table-height="500"
              :data-source="gongitem.supplyPriceType == '1' ? gongitem.uniteTableData : gongitem.areaTableData"
              :columns="gongitem.supplyPriceType == '1' ? uniteColumns : areaColumns"
              @handleRowChange="handleRowChange"
              @handleCancelSelect="handleCancelSelect"
            />
          </Row>
        </div>
        <Modal width="1000" v-model="gongitem.templateModal">
          <Row
            style="padding-top: 20px; padding-bottom: 16px"
            type="flex"
            align="middle"
          >
            <div>参照城市:</div>
            <Button
              type="primary"
              style="margin-left: 20px"
              :loading="setCityLoading"
              @click="showSetTempale(i)"
              >设置参照城市
            </Button>
          </Row>
          <Row class="format_table_wrap">
            <Table
              border
              height="400"
              :columns="templateColumns"
              :data="submitReferenceCityList"
            />
          </Row>
        </Modal>
        <city-table
          :Columns="setCityColumns"
          :dataSouce="setCityData"
          @handleBatch="handleBatch"
          @submitXiaoshouCity="submitXiaoshouCity"
          @defaultCity="defaultCity"
          @selectDropDownCity="tableSelectTemplateCity"
          @ChangeSetModal="ChangeSetModal"
          :groupCheckList="groupCheckList"
          :canZhaoDefault="defaultReferenceCityOptions"
          :canZhao="batchSetReferenceCityOptions"
          :cdisabled="cdisabled"
          :setModal="gongitem.setModal"
          :supplyUuid="supplyUuid"
          :supplyPriceType="gongitem.supplyPriceType"
          :templateDefaultCityUuid="templateDefaultCityUuid"
          :quyuSku="quyuSku"
          ref="cityTable"
        />
      </Card>
      <sale-city-dialog
        :dialogVisible="saleCityModal"
        :saleCityList="saleCityData"
        :hasSelectCityList="setSaleData"
        @set-sale-city="setSaleCity"
        @select-area-confirm="confirmSaleCity"
      />
    </div>
  </div>
</template>

<script>
import { ApiRequest } from '@api/basePage';
import supply from '@/components/commodity/getSupply.vue';
import SaleCityDialog from '@/components/commodity/selectSaleCityDialog';
import CityTable from '@/components/CityTable';
import SkusTable from '@/components/skusTable';
import {
  SUPPLY_SKUINFO_COLUMNS,
  AREA_COLUMNS,
  UNITE_COLUMNS,
  SET_CITY_COLUMNS,
  REFER_CITY_RELATION_COLUMNS
} from '@/constants/supplyColumns';
import { handlePriceChangeForSingleAdd, hasEmptyPriceForSingle } from '@/utils/price';

export default {
  components: {
    supply,
    SaleCityDialog,
    CityTable,
    SkusTable
  },
  props: {
    topinfo: {
      type: Object,
      // eslint-disable-next-line vue/require-valid-default-prop
      default: {
        isSaleMultiUnit: '2',
        isPurchaseMultiUnit: '2'
      }
    }
  },
  data () {
    return {
      spinShow: false,
      tableLoading: false,
      setCityLoading: false,
      setSaleData: [], // 销售区域已选集合
      submitReferenceCityList: [], // 参照城市提交数据
      templateDefaultCityUuid: '',
      areaNames: '',
      productUuid: '',
      state: '',
      isSaleMultiUnit: '', // 是否钢材 1-是 2-否
      saleCityModal: false,
      saleCityData: [],
      quyuSku: [],
      areaCodes: '',
      chooseAll: '',
      setCityData: [],
      cdisabled: false,
      groupCheckList: [],
      batchSetReferenceCityOptions: [], // 批量设置参照城市下拉列表数据
      defaultReferenceCityOptions: [], // 默认参照城市下拉数据
      batchBtn: false, // 是否前往批量
      isNewAddRel: false, // 是否通过新增获取 供货信息
      isNewAddPrice: false, // 是否通过新增获取 供价信息
      supplyUuid: '',
      gong: [
        {
          templateModal: false,
          setModal: false,
          checkAll: [],
          supplySkuInfoList: [], // 供货信息维护列表
          whoPayFreight: '', // 运费承担方
          supplyPriceType: '1',
          uniteTableData: [], // 统一定价列表
          areaTableData: []
        }
      ],
      // 供货城市的按钮状态
      setModalLoading: true,
      saleAreaNoList: [], // 保存销售区域编码
      // 供货城市弹框输入框
      formInline: {
        lossRatios: 1, // 批量输入成本比例
        select: '' // 参照城市
      },
      // 供货城市选中的数据
      selectionList: [],
      // 设置参照城市表头
      setCityColumns: SET_CITY_COLUMNS,
      // 参照城市关系表头
      templateColumns: REFER_CITY_RELATION_COLUMNS,
      // 供货信息
      supplySkuInfoColumns: SUPPLY_SKUINFO_COLUMNS,
      // 供货价格信息 - 统一
      uniteColumns: UNITE_COLUMNS,
      // 供货价格信息 - 区域
      areaColumns: AREA_COLUMNS,
      // 运费承担方
      freightPayer: '',
      taxRateInvoiceInfo: {
        taxRate: '',
        invoiceType: '',
        invoiceTypeName: ''
      }
    };
  },
  created () {
    this.productUuid = this.$route.query.productUuid;
    this.state = this.$route.query.state;
  },
  watch: {
    topinfo: {
      handler (val, oldName) {
        if (val.isSaleMultiUnit === '2' && val.isPurchaseMultiUnit === '2') {
          this.getAllAreaFromScrm();
          this.getDefaultData(0, val.productUuid); // 获取初始信息
        }
        this.templateDefaultCityUuid = val.mainCityCode;
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    // 更换弹框状态
    ChangeSetModal (data) {
      this.gong[0].setModal = data;
    },
    // 默认城市发生变化
    defaultCity (e) {
      this.templateDefaultCityUuid = e;
    },
    // 选择表格中的  参照城市
    tableSelectTemplateCity (data) {
      this.setCityData = data;
    },
    // 设置参照城市-提交
    submitXiaoshouCity (data) {
      const { submitReferenceCityList, templateModal, unarr = [] } = data;
      const { taxRate, invoiceType, invoiceTypeName } = this.taxRateInvoiceInfo;
      if (unarr.length != 0) {
        unarr.forEach(item => {
          item.taxRate = taxRate
          item.invoiceType = invoiceType
          item.invoiceTypeName = invoiceTypeName
        })
      }
      this.templateModal = templateModal;
      this.submitReferenceCityList = submitReferenceCityList;
      this.unarr = unarr;
      this.$set(this.gong[0], 'areaTableData', unarr);
    },
    // 批量修改的方法
    handleBatch (data) {
      const { formInline, newDataSouce } = data;
      this.formInline = formInline;
      this.setCityData = newDataSouce;
    },
    // 供货进价方式切换
    handleSupplyMethodChange () {
      this.submitReferenceCityList = [];
    },
    // 获取供应商
    getSupply (row) {
      this.submitReferenceCityList = [];
      this.supplyUuid = row.supplierCode;
      this.freightPayer = row.freightPayer;
      this.taxRateInvoiceInfo = {
        taxRate: row.taxRate,
        invoiceType: row.invoiceType,
        invoiceTypeName: row.invoiceTypeName,
      }
      const { areaTableData, uniteTableData } = this.gong[0]
      if (areaTableData.length != 0) {
        this.gong[0].areaTableData = areaTableData.map(item => {
          let itemData = { ...item, ...this.taxRateInvoiceInfo }
          return itemData;
        })
        this.gong[0].areaTableData.forEach(item => {
          this.handleRowChange(item)
        })
      }
      if (uniteTableData.length != 0) {
        this.gong[0].uniteTableData = uniteTableData.map(item => {
          let itemData = { ...item, ...this.taxRateInvoiceInfo }
          return itemData;
        })
        this.gong[0].uniteTableData.forEach(item => {
          this.handleRowChange(item)
        })
      }
    },
    // 获取初始信息
    getDefaultData (i, productUuid) {
      var that = this;
      let data = {
        productUuid: productUuid
      };
      this.spinShow = true;
      this.tableLoading = true;
      ApiRequest(
        '/sysback/supplyproductrel/getAllInfoByProductUuid',
        'post',
        data,
        true
      )
        .then(res => {
          this.tableLoading = false;
          this.spinShow = false;
          if (res.retData == null || res.retData.length === 0) {
            that.batchBtn = true;
            return;
          }
          const result = res.retData[0];
          if (result.supplyInfoDTO) {
            this.taxRateInvoiceInfo = {
              invoiceType: result.supplyInfoDTO.invoiceType,
              invoiceTypeName: result.supplyInfoDTO.invoiceTypeName,
              taxRate: result.supplyInfoDTO.taxRate
            }
          }
          // 头部 信息
          that.supplyUuid = result.supplyUuid;
          that.gong[i].supplyName = result.supplyName;

          that.gong[i].whoPayFreight = result.whoPayFreight;
          that.gong[i].unit = result.supplyProductInfo.unitName;
          // 参照城市已选列表
          this.submitReferenceCityList = result.listArea;
          // supplyPriceType
          if (result.supplyPriceType) {
            that.gong[i].supplyPriceType = result.supplyPriceType;
          }
          // 销售区域信息
          let listSaleArea = result.listSaleArea;

          listSaleArea.forEach(item => {
            that.saleCityData.forEach(ele => {
              if (ele.areaCode == item.saleAreaNo) {
                that.setSaleData.push(ele);
                ele['_checked'] = true;
              }
            });
          });
          that.confirmSaleCity(true);

          this.saleAreaNoList = listSaleArea.map(item => item.saleAreaNo);
          this.loadSaleAreaInfo(result.supplyInfoDTO)
          if (this.setSaleData.length == 0) {
            this.$Message.warning('请选择销售区域');
          }

          // 供货信息 列表
          if (result.listSkuRel == null || result.listSkuRel.length == '0') {
            that.isNewAddRel = true;
          } else {
            result.listSkuRel.forEach(element => {
              element.specDetailStr = result.supplyProductInfo.specDetailStr;
            });
            that.gong[i].supplySkuInfoList = result.listSkuRel;
          }
          // 供价信息 列表
          if (result.supplyPriceType == null || result.supplyPriceType.length == '0') {
            that.isNewAddPrice = true;
          } else {
            result.listPrice.forEach(element => {
              element.purchasePriceType = parseInt(
                result.listPrice[i].purchasePriceType
              );
              element.addPriceType = parseInt(result.listPrice[i].addPriceType);
              element.saleAreaName = element.templateCitySaleAreaName;
              element.saleAreaUuid = element.templateCitySaleAreaNo;
              element.mainUnitStr = element.supplyProductInfo ? element.supplyProductInfo.unitName : '';
              if (result.supplyInfoDTO) {
                element.invoiceType = result.supplyInfoDTO.invoiceType
                element.invoiceTypeName = result.supplyInfoDTO.invoiceTypeName
                element.taxRate = result.supplyInfoDTO.taxRate
              }
              this.handleRowChange(element)
            });
            if (result.supplyPriceType == '1') {
              let unarr = [];
              result.listPrice.forEach(function (item, index) {
                if (JSON.stringify(unarr).indexOf(JSON.stringify(item.skuNo)) == -1) {
                  unarr.push(item);
                }
              });
              that.gong[i].uniteTableData = unarr;
            } else {
              that.gong[i].areaTableData = result.listPrice;
              const list = result.listPrice.map(item => ({ ...item }));
              let unarr = [];
              list.forEach(function (item) {
                if (
                  JSON.stringify(unarr).indexOf(JSON.stringify(item.skuNo)) ==
                  -1
                ) {
                  unarr.push(item);
                }
              });
              unarr.forEach(ele => {
                ele.purchasePriceType = 1;
              });
              that.gong[i].uniteTableData = unarr;
            }
          }
          // 执行 新增方法 获取信息
          that.NewAddGetData();
        })
        .catch(() => {
          this.tableLoading = false;
          this.spinShow = false;
        });
    },

    // 通过 新增的方法 获取默认数据
    NewAddGetData () {
      var that = this;
      let data = {
        productUuid: that.productUuid
      };
      that.quyuSku = [];
      ApiRequest(
        '/sysback/skuaudit/list/getAuditSkuByProduct',
        'post',
        data,
        true
      ).then(res => {
        if (res.retStatus == '1') {
          let result = res.retData;
          // 预留sku信息  以便后面 根据参照城市处理区域供价的信息
          result.forEach(function (item, index) {
            let quyuObj = {
              skuNo: item.skuNo,
              specDetailStr: item.specDetailStr,
              addPriceType: that.topinfo.addPriceType,
              purchaseUnitStr: item.purchaseUnitStr,
              unitName: item.unitName,
              mainUnitStr: item.mainUnitStr
            };
            that.quyuSku.push(quyuObj);
          });
          if (that.isNewAddRel) {
            // 给 供货信息 赋值
            result.forEach((item) => {
              let obj = {
                skuNo: item.skuNo,
                specDetailStr: item.specDetailStr,
                productUuid: item.productUuid,
                purchaseUnitStr: item.purchaseUnitStr,
                unitName: item.unitName,
                mainUnitStr: item.mainUnitStr,
                factoryCode: '',
                factoryName: '',
                purchasePrice: '',
                minOrderGoodsNum: 0,
                warrantyStatus: '',
                warrantyDay: 0,
                exchangeGoodsStatus: '',
                exchangeGoodsDay: '',
                exchangeGoodsCondition: '',
                returnGoodsStatus: '',
                returnGoodsDay: 0,
                returnGoodsCondition: '',
                minReOrExNum: 0,
                minSaleImperfectionsNum: 0,
                productPacking: '',
                otherPromise: '',
                addPriceType: that.topinfo.addPriceType
              };
              that.gong[0].supplySkuInfoList.push(obj);
            });
          } else if (that.isNewAddPrice) {
            const { invoiceType, invoiceTypeName, taxRate } = this.taxRateInvoiceInfo;
            result.forEach((item) => {
              if (that.gong[0].supplyPriceType == '1') {
                let obj = {
                  skuNo: item.skuNo,
                  specDetailStr: item.specDetailStr,
                  productUuid: item.productUuid,
                  unitName: item.unitName,
                  mainUnitStr: item.mainUnitStr,
                  saleAreaName: item.templateCitySaleAreaName,
                  mainUnitUuid: '',
                  mainConvertRatio: '',
                  purchasePrice: 0,
                  mainPurchasePrice: 0,
                  purchasePriceType: 1,
                  addPriceType: that.topinfo.addPriceType,
                  freightRatio: 0,
                  packRatio: 0,
                  processChargesRatio: 0,
                  rebateRatio: 0,
                  mainUnitCostPrice: 0,
                  invoiceType,
                  invoiceTypeName,
                  taxRate
                };
                that.gong[0].uniteTableData.push(obj);
                /* 10-16 临时添加 */
                this.gong[0].supplySkuInfoList.forEach(value => {
                  value.addPriceType = that.topinfo.addPriceType;
                });
              }
            });
          }
        }
      });
    },
    // 获取 销售区域数据
    getAllAreaFromScrm () {
      let data = {};
      ApiRequest(
        '/sysback/supplyinfofromsrcm/getAllAreaFromScrm',
        'post',
        data,
        true
      ).then(res => {
        if (res.retStatus == '1') {
          this.saleCityData = res.retData;
        }
      });
    },
    // 展示弹窗
    showSelectArea () {
      this.saleCityModal = true;
    },

    // 勾选销售区域
    setSaleCity (params) {
      const { data, chooseType } = params;
      this.setSaleData = data;
      this.chooseAll = chooseType;
    },

    // 确认销售城市
    confirmSaleCity (isInit) {
      if (!isInit && this.setSaleData.length == 0) {
        return this.$Message.warning('请选择销售区域');
      }
      let codeList = [];
      let cityNameList = [];
      this.setSaleData.forEach(function (item, index) {
        if (!codeList.includes(item.areaCode)) {
          codeList.push(item.areaCode)
        }
        if (!cityNameList.includes(item.areaName)) {
          cityNameList.push(item.areaName)
        }
      });
      this.areaCodes = codeList.join(',');
      this.areaNames = cityNameList.join(',');
      if (!isInit) {
        this.saleCityModal = false;
        this.submitReferenceCityList = [];
      }
      this.saleAreaNoList = codeList;
    },

    // 点击 设置 (展示第一层弹窗)
    handleSetCityLink (index, val) {
      if (!this.areaCodes) {
        return this.$message.warning('请选择销售区域')
      }
      if (!this.supplyUuid) {
        return this.$Message.warning('请先选择供应商');
      }
      this.gong[index].templateModal = true;
    },

    // 展示设置参照城市  (第二层弹窗)
    showSetTempale (i) {
      var that = this;
      that.setCityData = [];
      let data = {
        areaCode: this.areaCodes
      };
      this.setCityLoading = true;
      ApiRequest(
        '/sysback/supplyinfofromsrcm/getSupplyCityByAreaCodes',
        'post',
        data,
        true
      ).then(res => {
        this.setCityLoading = false;
        if (res.retStatus == '1') {
          res.retData.forEach(function (item, index) {
            item.isSupply = '';
            item.templateCity = '';
            item.templateCityUuid = '';
            item.buyPriceRatio = 1;
            item.costPriceRatio = 1;
          });
          that.gong[i].setModal = true;
          res.retData.forEach(item => {
            let obj = {
              ...item,
              _disabled: false
            };
            obj.saleCityName = item.cityName;
            obj.saleCityNo = item.cityCode;
            obj.saleProvinceName = item.provinceName;
            obj.saleProvinceNo = item.provinceCode;
            obj.productUuid = that.productUuid;
            obj.templateCitySaleAreaNo = item.areaCode;
            obj.templateCitySaleAreaName = item.areaName;
            that.setCityData.push(obj);
          });
          that.getSuppluCity();
          that.batchSetReferenceCityOptions = res.retData.map(item => ({
            cityCode: item.cityCode,
            cityName: item.cityName,
            templateCitySaleAreaNo: item.areaCode,
            templateCitySaleAreaName: item.areaName,
            disabled: true
          }));
        }
      });
    },

    // 获取 供货城市 (参照城市第二层弹窗)
    getSuppluCity () {
      let data = {
        supplierCode: this.supplyUuid
      };
      ApiRequest(
        '/sysback/supplyinfofromsrcm/getSupplyProvinceBySupplyNo',
        'post',
        data,
        true
      ).then(res => {
        if (res.retStatus == '1') {
          this.groupCheckList = res.retData;
          this.defaultReferenceCityOptions = res.retData.map(item => ({
            cityCode: item.cityCode,
            cityName: item.cityName
          }));
          if (this.topinfo.mainCityCode) {
            let flag = true;

            this.defaultReferenceCityOptions.forEach(item => {
              if (item.cityCode == this.topinfo.mainCityCode) {
                flag = false;
              }
            });
            if (flag) {
              this.defaultReferenceCityOptions.push({
                cityCode: this.topinfo.mainCityCode,
                cityName: this.topinfo.mainCityName
              });
            }
          }
          this.handleCheckAll(this.gong[0], 0);
        }
      });
    },

    // 选择供货城市
    selectGonghuoCity (e, i) {
      var that = this;
      if (that.formInline.select && !e.includes(that.formInline.select)) {
        that.formInline.select = '';
      }
      this.batchSetReferenceCityOptions.forEach(item => {
        item.disabled = true;
        e.forEach(t => {
          if (t === item.cityCode) {
            item.disabled = false;
          }
        });
      });
      let select = [];
      that.gong[i].checkAll.forEach(function (item, index) {
        that.groupCheckList.forEach(function (em, ex) {
          if (em.cityCode == item) {
            select.push(em);
          }
        });
      });

      let defaultReferenceCityOptions = [];
      that.gong[i].checkAll.forEach(item => {
        this.batchSetReferenceCityOptions.forEach(otem => {
          if (item == otem.cityCode) {
            defaultReferenceCityOptions.push(otem);
          }
        });
      });
      defaultReferenceCityOptions = [...new Set(defaultReferenceCityOptions)];
      this.defaultReferenceCityOptions = defaultReferenceCityOptions;
      that.setCityData.forEach(function (item, index) {
        item._disabled = false;
        item.isSupply = '2';
        select.forEach(function (em, ex) {
          if (item.saleCityNo == em.cityCode) {
            item.isSupply = '1';
            item.templateCityName = em.cityName;
            item.templateCityUuid = em.cityCode;
            item.buyPriceRatio = 1;
            item.costPriceRatio = 1;
            // 如果相等的话就把表格禁用
            if (
              item.saleCityNo == item.templateCityUuid &&
              that.gong[i].supplyPriceType == '1'
            ) {
              item._disabled = true;
            }
          }
        });
        that.batchSetReferenceCityOptions.forEach(ele => {
          if (
            item.isSupply !== '1' &&
            ele.disabled &&
            item.templateCityUuid == ele.cityCode
          ) {
            item.templateCityUuid = '';
          }
        });
      });
    },

    // 删除该行数据
    deleterow (i, index) {
      this.gong[i].uniteTableData.splice(index, 1);
    },

    // 取消关联
    handleCancelSelect (data) {
      const { index } = data;
      if (this.gong[0].supplyPriceType == 1) {
        this.$delete(this.gong[0].uniteTableData, index);
      } else if (this.gong[0].supplyPriceType == 2) {
        this.$delete(this.gong[0].areaTableData, index);
      }
      this.$nextTick(() => {
        this.$Message.info('删除成功', 10);
      });
    },

    // 表格input发生变化
    handleRowChange (row) {
      handlePriceChangeForSingleAdd(row)
    },

    // 页面信息  保存
    async save () {
      var that = this;
      if (!this.areaCodes) {
        return this.$Message.warning('请设选择销售区域');
      }
      if (!this.supplyUuid) {
        return this.$Message.warning('请选择供应商');
      }
      if (this.submitReferenceCityList.length == 0) {
        return this.$Message.warning('请选择参照城市');
      }

      if (
        !this.templateDefaultCityUuid &&
        this.gong[0].supplyPriceType == '1'
      ) {
        return this.$Message.warning('请设置默认参照城市');
      }

      let list = [];
      let list3 = [];
      // 校验成本价是否大于零
      let submitData = [];
      if (this.gong[0].supplyPriceType == '1') {
        submitData = this.gong[0].uniteTableData;
      } else {
        submitData = this.gong[0].areaTableData;
      }
      const { hasEmptyVal, msg } = hasEmptyPriceForSingle(submitData)
      if (hasEmptyVal) {
        return this.$message.warning(msg);
      }

      this.gong.forEach(function (item, index) {
        item.supplySkuInfoList.forEach(function (otem, ondex) {
          otem.supplyUuid = that.supplyUuid;
          otem.isMainSupply = '1';
        });
        list = item.supplySkuInfoList;
        if (item.supplyPriceType == '1') {
          item.uniteTableData.forEach(function (otem, ondex) {
            otem.supplyUuid = that.supplyUuid;
            otem.productUuid = that.productUuid;
            otem.templateCitySaleAreaNo = otem.saleAreaUuid;
            otem.isMainSupply = '1';
          });
          list3 = item.uniteTableData;
        } else {
          item.areaTableData.forEach(function (otem, ondex) {
            otem.supplyUuid = that.supplyUuid;
            otem.productUuid = that.productUuid;
            otem.templateCitySaleAreaNo = otem.saleAreaUuid;
            otem.isMainSupply = '1';
          });
          list3 = item.areaTableData;
        }
      });
      let data = {
        productUuid: this.productUuid,
        areaCodes: this.areaCodes
      };
      // 入参集合所需item属性
      const listPickKeys = [
        'supplyUuid', 'productUuid', 'skuNo', 'factoryCode', 'factoryName',
        'purchasePrice', 'minOrderGoodsNum', 'warrantyStatus', 'warrantyDay',
        'exchangeGoodsStatus', 'exchangeGoodsDay', 'exchangeGoodsCondition',
        'returnGoodsStatus', 'returnGoodsDay', 'returnGoodsCondition',
        'minReOrExNum', 'minSaleImperfectionsNum', 'productPacking', 'otherPromise'
      ]
      this.$emit('updateLoadingState', true);
      ApiRequest(
        '/sysback/supplysaleareaproductrel/createRel?chooseAll=' +
          this.chooseAll,
        'post',
        data,
        true
      ).then(res => {
        if (res.retStatus == '1') {
          this.saleCityModal = false;
          this.cdisabled = false;
          ApiRequest(
            '/sysback/supplyskurel/batchCreateSupplySkuRel?batchState=prepareing',
            'post',
            list.map(item => _.pick(item, listPickKeys))
          ).then(res => {
            if (res.retStatus == '1') {
              that.save3();
            } else {
              this.$emit('updateLoadingState', false);
            }
          });
        } else {
          this.$emit('updateLoadingState', false);
        }
      });
    },

    async save3 () {
      var that = this;
      let list = [];
      let list3 = [];

      this.gong.forEach(function (item, index) {
        item.supplySkuInfoList.forEach(function (otem, ondex) {
          otem.supplyUuid = that.supplyUuid;
          otem.isMainSupply = '1';
        });
        list = item.supplySkuInfoList;
        if (item.supplyPriceType == '1') {
          item.uniteTableData.forEach(function (otem, ondex) {
            otem.supplyUuid = that.supplyUuid;
            otem.productUuid = that.productUuid;
            otem.templateCityUuid = that.templateDefaultCityUuid;
            otem.templateCitySaleAreaName = otem.saleAreaName;
            otem.templateCitySaleAreaNo = otem.saleAreaUuid;
            otem.isMainSupply = '1';
          });
          list3 = item.uniteTableData;
        } else {
          item.areaTableData.forEach(function (otem, ondex) {
            otem.supplyUuid = that.supplyUuid;
            otem.productUuid = that.productUuid;
            otem.templateCitySaleAreaName = otem.saleAreaName;
            otem.templateCitySaleAreaNo = otem.saleAreaUuid;
            otem.isMainSupply = '1';
          });
          list3 = item.areaTableData;
        }
      });
      // 参照城市设置提交
      ApiRequest(
        '/sysback/supplyarea/batchCreateSupplyArea',
        'post',
        this.submitReferenceCityList
      ).then(res => {
        if (res.retStatus == '1') {
          // 供货价格相关信息提交
          ApiRequest(
            '/sysback/supplyareaprice/batchCreateSupplyAreaPrice?batchState=prepareing',
            'post',
            list3
          ).then(res => {
            this.$emit('updateLoadingState', false);
            if (res.retStatus == '1') {
              this.$Message.success('保存成功');
              this.$router.push({
                name: 'commodityNotPerfection',
                query: { productUuid: this.productUuid }
              });
            }
          });
        } else {
          this.$emit('updateLoadingState', false);
        }
      });
    },

    gotoPage () {
      this.$router.push({
        path: '/commodity/commodityAccessManage/waitAccess/addSupply',
        query: { productUuid: this.productUuid, state: this.state }
      });
    },
    // 供货城市全选按钮
    handleCheckAll (data, i) {
      let cityCodeList = this.groupCheckList.map(item => item.cityCode);
      data.checkAll = cityCodeList;
      this.selectGonghuoCity(cityCodeList, i);
    },
    // 加载销售区域信息
    loadSaleAreaInfo (data) {
      if (this.saleAreaNoList.length != 0) return
      const relSaleCities = this.saleCityData.filter(item => item.manageAreaUuid == data?.supplyManagerAreaId)
      this.updateSaleAreaInfo(relSaleCities.map(item => item.areaCode))
    },
    // 更新销售区域信息
    updateSaleAreaInfo (areaCodes) {
      this.areaNames = this.saleCityData
        .filter(item => areaCodes.includes(item.areaCode))
        .map(item => item.areaName)
        .join('')
      this.areaCodes = this.saleCityData
        .filter(item => areaCodes.includes(item.areaCode))
        .map(item => item.areaCode)
        .join(',')
      this.saleAreaNoList = areaCodes
      this.setSaleData = areaCodes
    },
  }
};
</script>

<style lang="less" scoped>
.cardRow {
  padding: 8px 0;
}

.min-title {
  font-size: 14px;
  min-height: 50px;
  line-height: 50px;
  color: #17233d;
  font-weight: bold;
}

.ivu-form-item {
  margin-bottom: 0;
}
</style>
